package com.lemon.exam.common.converter;

import com.lemon.exam.common.entity.view.ViewClassGradeUserJob;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.lang.NonNull;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * 视图 view_class_grade_user_job 转换器
 *
 * @author Lemon
 * @since 2025/4/22 9:07
 */
@ReadingConverter
public class ClassGradeUserJobConverter implements Converter<Row, ViewClassGradeUserJob> {
    /**
     * 映射关系
     * 字段 -> 字段类型 -> 字段赋值方法
     */
    private static final Function<ViewClassGradeUserJob, List<Triple<String, Class<?>, Consumer<Object>>>> MAPPING = entity -> List.of(
            Triple.of("class_id", Long.class, v -> entity.setClassId((Long) v)),
            Triple.of("class_name", String.class, v -> entity.setClassName((String) v)),
            Triple.of("class_deleted", Integer.class, v -> entity.setClassDeleted((Integer) v)),
            Triple.of("grade_id", Long.class, v -> entity.setGradeId((Long) v)),
            Triple.of("grade_name", String.class, v -> entity.setGradeName((String) v)),
            Triple.of("grade_deleted", Integer.class, v -> entity.setGradeDeleted((Integer) v)),
            Triple.of("user_id", Long.class, v -> entity.setUserId((Long) v)),
            Triple.of("user_name", String.class, v -> entity.setUserName((String) v)),
            Triple.of("user_username", String.class, v -> entity.setUserUsername((String) v)),
            Triple.of("user_status", Integer.class, v -> entity.setUserStatus((Integer) v)),
            Triple.of("user_deleted", Integer.class, v -> entity.setUserDeleted((Integer) v)),
            Triple.of("job_id", Long.class, v -> entity.setJobId((Long) v)),
            Triple.of("job_name", String.class, v -> entity.setJobName((String) v)),
            Triple.of("job_deleted", Integer.class, v -> entity.setJobDeleted((Integer) v))
    );

    @Override
    @NonNull
    public ViewClassGradeUserJob convert(Row source) {
        RowMetadata meta = source.getMetadata();
        ViewClassGradeUserJob entity = new ViewClassGradeUserJob();
        MAPPING.apply(entity).forEach(mapping -> {
            if (meta.contains(mapping.getLeft())) {
                mapping.getRight().accept(source.get(mapping.getLeft(), mapping.getMiddle()));
            }
        });
        return entity;
    }
}
